package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @version 1.0
 * @Author qXing
 * @Date 2025/9/2 16:16
 * @account监听器：监听消息队列
 */
@Component
@Slf4j
public class AccountRecevier {
    @Autowired
    private UserAccountService userAccountService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    //Message message: 原始的RabbitMQ消息对象，包含消息属性和头信息
    //Channel channel: RabbitMQ通道对象，用于进行消息确认等操作
    public void userRegister(Long userId, Message message, Channel channel){
        System.out.println("用户注册成功，用户id"+userId);
        try {
            if (null != userId){
                //代表此时获取到了用户id
                //调用服务层方法,给新注册用户赋账户初值
                userAccountService.userRegister(userId);
            }
        } catch (Exception e){
            //可以采用redis重试
            //如果大于三次仍不成功，则落盘到数据库，存储信息
            log.error(e.getMessage(),e);
        }
        try{
            //etDeliveryTag()获取消息的唯一标识符
            //第二个参数false表示不批量确认，只确认当前消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e){
            throw new RuntimeException(e);
        }
    }
}
